﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;


namespace SPDateChange
{
    public partial class UpdateDocs : System.Windows.Forms.Form
    {
        public UpdateDocs()
        {
            InitializeComponent();
            dt = new DataTable();
            dt.Columns.Add("ID");
            dt.Columns.Add("Name");
            dt.Columns.Add("Modified");
            dt.Columns.Add("Created");
            dt.Columns.Add("ModifiedBy");
            dt.Columns.Add("CreatedBy");

        }

        private void button2_Click(object sender, EventArgs e)
        {
            Environment.Exit(0);
        }

        DataTable dt = new DataTable();

        //TODO: handle filtering 
        private void cmdLoad_Click(object sender, EventArgs e)
        {
            using (SPSite ctx = new SPSite(txtSiteUrl.Text))
            {
                using (SPWeb web = ctx.OpenWeb())
                {
                    //TODO: Handle large lists
                    SPList list = web.Lists[txtLibrary.Text];
                    foreach (SPListItem item in list.Items)
                    {
                        var row = dt.NewRow();
                        row["ID"] = item.ID;
                        row["Name"] = item.Name;
                        row["Modified"] = item["Modified"];

                        SPFieldUser field1 = item.Fields[SPBuiltInFieldId.Editor] as SPFieldUser;
                        if (field1 != null)
                        {
                            SPFieldUserValue fieldValue = field1.GetFieldValue((string)item[SPBuiltInFieldId.Editor]) as SPFieldUserValue;
                            row["ModifiedBy"] = fieldValue.User.LoginName;
                        }


                        row["Created"] = item["Created"];
                        SPFieldUser field = item.Fields[SPBuiltInFieldId.Author] as SPFieldUser;
                        if (field != null)
                        {
                            SPFieldUserValue fieldValue = field.GetFieldValue((string)item[SPBuiltInFieldId.Author]) as SPFieldUserValue;
                            row["CreatedBy"] = fieldValue.User.LoginName;
                        }

                        dt.Rows.Add(row);
                    }

                    gdDocs.DataSource = dt;

                }
            }



        }

        private void cmdUpdate_Click(object sender, EventArgs e)
        {


            int docs = 0;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite ctx = new SPSite(txtSiteUrl.Text))
                {
                    using (SPWeb web = ctx.OpenWeb())
                    {
                        SPList list = web.Lists[txtLibrary.Text];
                        foreach (DataGridViewRow item in gdDocs.Rows)
                        {

                            var cell = item.Cells["select"];
                            bool IsSelected = false;

                            if (cell.Value != null)
                            {
                                IsSelected = bool.Parse(cell.Value.ToString());
                            }

                            if (IsSelected)
                            {


                                var IDCell = item.Cells["ID"];
                                int itemID = int.Parse((string)IDCell.Value);
                                var listitem = list.GetItemById(itemID);
                                var ModifiedDate = DateTime.Parse((string)item.Cells["Modified"].Value);
                                var CreatedBy = (string)item.Cells["CreatedBy"].Value;
                                var ModifiedBy = (string)item.Cells["ModifiedBy"].Value;
                                var CreatedDate = DateTime.Parse((string)item.Cells["Created"].Value);
                                listitem[SPBuiltInFieldId.Created] = SPUtility.CreateISO8601DateTimeFromSystemDateTime(CreatedDate.ToUniversalTime());
                                listitem[SPBuiltInFieldId.Modified] = SPUtility.CreateISO8601DateTimeFromSystemDateTime(ModifiedDate.ToUniversalTime());

                                SPUser createdByUser = web.EnsureUser(CreatedBy);
                                SPUser modifiedByUser = web.EnsureUser(ModifiedBy);


                                listitem["Author"] = createdByUser.ID + ";#" + createdByUser.Name;
                                listitem["Editor"] = modifiedByUser.ID + ";#" + modifiedByUser.Name;

                                listitem.SystemUpdate(false);
                                docs++;
                            }
                        }
                    }


                }

            });

            MessageBox.Show(string.Format("{0} documents updated", docs));


        }

        private void PasteText()
        {
            string s = Clipboard.GetText();
            string[] lines = s.Split('\n');
          
           
            int linesSelected = lines.Length;
            int lineNum = -1;
            int colNum = -1;

            Dictionary<int, int> lineMap = new Dictionary<int, int>();
            Dictionary<int, int> colMap = new Dictionary<int, int>();

            for (int i = gdDocs.SelectedCells.Count - 1; i >= 0; i--)
            {
                DataGridViewCell cell = gdDocs.SelectedCells[i];
                if (!lineMap.ContainsKey(cell.RowIndex))
                {
                    lineNum++;
                    lineMap.Add(cell.RowIndex, lineNum);
                }

                if (!colMap.ContainsKey(cell.ColumnIndex))
                {
                    colNum++;
                    colMap.Add(cell.ColumnIndex, colNum);
                }



                int lineIndex = lineMap[cell.RowIndex];
                int colIndex = colMap[cell.ColumnIndex];
                if (lineIndex < lines.Length)
                {
                    var line = lines[lineIndex];
                    var cells = line.Split('\t');
                    if (colIndex < cells.Length)
                    {
                        cell.Value = cells[colIndex];
                    }

                }
            }



        }

        
        private void CopyText()
        {
            DataObject d = gdDocs.GetClipboardContent();
            Clipboard.SetDataObject(d);
        }


        private void GridDocuments_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Control && e.KeyCode == Keys.C)
            {
                CopyText();
                e.Handled = true;
            }
            else if (e.Control && e.KeyCode == Keys.V)
            {
                PasteText();
                e.Handled = true;
            }
        }

        private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            PasteText();
            //PasteClipboard();
        }

        private void copyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            CopyText();
        }

        private void UpdateDocs_Load(object sender, EventArgs e)
        {
            // add checkbox header
            Rectangle rect = gdDocs.GetCellDisplayRectangle(1, -1, true);
            // set checkbox header to center of header cell. +1 pixel to position correctly.
            rect.X = rect.Location.X + (rect.Width / 4);
 
            CheckBox checkboxHeader = new CheckBox();
            checkboxHeader.Name = "checkboxHeader";
            checkboxHeader.Size = new Size(18, 18);
            checkboxHeader.Location = rect.Location;
            checkboxHeader.CheckedChanged += new EventHandler(checkboxHeader_CheckedChanged);
            gdDocs.Controls.Add(checkboxHeader);

        }

        void checkboxHeader_CheckedChanged(object sender, EventArgs e)
        {

            CheckBox sn = sender as CheckBox;

            for (int i = 0; i < gdDocs.RowCount; i++)
            {
                gdDocs.Rows[i].Cells[0].Value = sn.Checked.ToString().ToLower();
            }

        }




    }
}
